package threadcoreknowledge.stopthreads;

/**
 * 6.带有sleep的中断线程的写法
 * 直接抛异常   sleep interrupted
 * https://javaweixin6.blog.csdn.net/article/details/108068653
 */
public class RightWayStopThreadWithSleep {

    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            int num = 0;
            try {
                while (num <= 300 && !Thread.currentThread().isInterrupted()) {
                    if (num % 100 == 0) {
                        System.out.println(num + "是100的倍数");
                    }
                    num++;
                }

                //执行完成循环累加后, 执行sleep, 此时主线程给出中断信号
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

        //当子线程 正在休眠的过程中, 去进行线程的中断.
        //因此要等子线程执行到  Thread.sleep(1000);这一行代码
        //此处的  Thread.sleep(500); 是给子线程  循环0到300的时间用的
        Thread.sleep(500);

        //子线程执行完成0到300累加后, 在子线程sleep的过程中, 去给出中断的信号
        thread.interrupt();
    }
}
